package com.hyper_yang._05_juc.chap07;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 演示  生产者和消费者之间通信
 *
 *      以前实现方式：
 *          synchronized + wait/notify/notifyAll
 *          Lock + Condition(  await/signal/signalAll  )
 *
 *     现在实现方式：
 *          利用BlockingQueue实现。
 */
public  class BlockingQueueDemo2 {

    public static void main(String[] args) {

        //控制生产者和消费者对馒头的使用。
        BlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue<>(3); //队列长度

        new Thread(()->{
            try {
                for (int i = 1; i <= 10; i++) {
                    blockingQueue.put(i);
                    System.out.println(Thread.currentThread().getName() + "\t" + "生产馒头编号："+i);
                    Thread.sleep(2000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"生产者").start();

        new Thread(()->{
            try {
                for (int i = 1; i <= 10; i++) {
                    Integer number = blockingQueue.take(); //存放时馒头编号。
                    System.out.println(Thread.currentThread().getName() + "\t" + "消费馒头编号："+number);
                    Thread.sleep(4000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"消费者").start();
    }
}
